<?php

use App\Models\System\Admin;
use App\Models\System\Module;
use Illuminate\Support\Facades\Cache;

if (! function_exists('hasPermission')) {
	/**
	 * 验证用户是否拥有某项权限
	 *
	 * Date: 21/03/2018
	 * @author George
	 * @param string $code
	 * @return bool
	 */
	function hasPermission(string $code): bool
	{
		if ($this->hasPosition()) {
			$permissions = Cache::remember("users:$this->id:permissions", 30, function () {
				return Auth::user()->position->permissions()->pluck('code');
			});
			return $permissions->contains($code);
		}
	}
}

if (! function_exists('memberOfCompany')) {
	/**
	 * 验证用户是否隶属于某个公司
	 *
	 * Date: 21/03/2018
	 * @author George
	 * @param int $company
	 * @return bool
	 */
	function memberOfCompany(int $company): bool
	{
		return Auth::user()->company_id = $company;
	}
}

if (! function_exists('memberOfProject')) {
	/**
	 * 验证用户是否隶属于某个项目
	 *
	 * Date: 21/03/2018
	 * @author George
	 * @param int $project
	 * @return bool
	 */
	function memberOfProject(int $project): bool
	{
		return Auth::user()->company_id = $project;
	}
}

if (! function_exists('hasModule')) {
	/**
	 * 验证公司是否拥有某个模块
	 *
	 * Date: 21/03/2018
	 * @author George
	 * @param string $code
	 * @return bool
	 */
	function hasModule(string $code): bool
	{
		$query = Module::query();
		$module = $query->where('code', $code)->first();

		if ($module->pricing) {

		}
	}
}

if (! function_exists('isManager')) {
	/**
	 * 验证用户是否为公司管理员
	 *
	 * Date: 25/03/2018
	 * @author George
	 * @return bool
	 */
	function isManager(): bool
	{
		$user = Auth::user();
		return (boolean) $user->manager;
	}
}

if (! function_exists('isAdmin')) {
	/**
	 * 验证用户是否为平台管理员
	 *
	 * Date: 25/03/2018
	 * @author George
	 * @return bool
	 */
	function isAdmin(): bool
	{
		$user = Auth::user();
		return $user instanceof Admin ? true : false;
	}
}

